package psd.model.Prolog.Converters;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.dom.CompilationUnit;

import psd.model.IConverter;
import psd.model.Prolog.FactGenerationToolbox;
import psd.model.Prolog.PrologConverter;


public class PrologCompilationUnitConverter extends PrologConverter implements
		IConverter<CompilationUnit> {

	public PrologCompilationUnitConverter(FactGenerationToolbox toolbox) {
		super(toolbox);
		// TODO Auto-generated constructor stub
	}

	@Override
	public boolean convert(CompilationUnit node) {
		initAnnotations(node);
		initComments(node);
		String id = idResolver.getID(node);
		List defList = new ArrayList();
		List importList = new ArrayList();
		if (node.getPackage() != null) {
			writer.writeFact("sl_argT", new String[] { idResolver.getID(node),
					"package",
					Integer.toString(node.getPackage().getStartPosition()),
					Integer.toString(node.getPackage().getLength()) });
		}
		importList.addAll(node.imports());
		defList.addAll(node.types());
		writeSourceFolderS();
		String fileS_ID = idResolver.getID();
//		String args[] = { fileS_ID, getUnresolvedSrcFolderId(), quote(fileName) };
//		writer.writeFact("fileS", args);
		String defs = idResolver.getIDs(defList);
		String imports = idResolver.getIDs(importList);
		String pckg;
		if (node.getPackage() == null) {
			pckg = "defaultPackage";
		} else {
			pckg = idResolver.getID(node.getPackage());
		}
		String compilationUnitArgs[] = { id, pckg, fileS_ID, imports, defs };
		writer.writeFact("compilationUnitT", compilationUnitArgs);
		writer.writeFact("slT", new String[] { idResolver.getID(node),
				Integer.toString(node.getStartPosition()),
				Integer.toString(node.getLength()) });
		writer.writeFact("modified_file", new String[] { fileS_ID });
		return true;
	}

	private void writeSourceFolderS() {
		String unresolvedSrcFolderId = getUnresolvedSrcFolderId();
		String unresolvedProjectId = (new StringBuilder("projectS(")).append(
				quote(iCompilationUnit.getResource().getProject().getName()))
				.append(")").toString();
		String srcFolderArgs[] = {
				unresolvedSrcFolderId,
				unresolvedProjectId,
				quote(getPackageFragmentRoot().getResource()
						.getProjectRelativePath().toString()) };
		writer.writeFact("sourceFolderS", srcFolderArgs);
	}

	private IJavaElement getPackageFragmentRoot() {
		IJavaElement pfr;
		for (pfr = iCompilationUnit.getParent(); pfr.getElementType() != 3; pfr = pfr
				.getParent()) {
		}
		return pfr;
	}

	private String getUnresolvedSrcFolderId() {
		return (new StringBuilder("sourceFolderS(")).append(
				quote(iCompilationUnit.getResource().getProject().getName()))
				.append(",").append(
						quote(getPackageFragmentRoot().getResource()
								.getProjectRelativePath().toString())).append(
						")").toString();
	}

	private void initAnnotations(CompilationUnit node) {
//		annotations = new Hashtable();
//		System.out.println();
//		for (Iterator iter = node.getCommentList().iterator(); iter.hasNext();) {
//			Comment comment = (Comment) iter.next();
//			if (comment.isBlockComment()) {
//				try {
//					annotations.put((new StringBuilder())
//							.append(
//									(comment.getStartPosition() + comment
//											.getLength()) - 1).toString(),
//							parseAnnotation(getTextForNode(comment, 2, -2)));
//				} catch (IllegalArgumentException _ex) {
//				}
//			}
//		}

	}
	
//	 private GenericAnnotation parseAnnotation(String text)
//     throws IllegalArgumentException
// {
//     if(text.startsWith(" @"))
//     {
//         text = text.substring(1);
//     }
//     if(!text.startsWith("@"))
//     {
//         throw new IllegalArgumentException();
//     }
//     StringTokenizer tokenizer = new StringTokenizer(text, "@(,) \n\r\t");
//     List args = new ArrayList();
//     String name;
//     if(tokenizer.hasMoreTokens())
//     {
//         name = checkToken(tokenizer.nextToken());
//     } else
//     {
//         throw new IllegalArgumentException();
//     }
//     for(; tokenizer.hasMoreElements(); args.add(checkToken(tokenizer.nextToken()))) { }
//     return new GenericAnnotationImpl(name, args);
// }


	private void initComments(CompilationUnit node) {
		// List blockOrlineCommentList = new ArrayList();
		// for(Iterator iter = node.getCommentList().iterator();
		// iter.hasNext();)
		// {
		// Comment comment = (Comment)iter.next();
		// if(!comment.isDocComment())
		// {
		// blockOrlineCommentList.add(comment);
		// List starterListRight = new ArrayList(1);
		// List starterListLeft = new ArrayList(1);
		// starterListRight.add(comment);
		// int distanceToTheRight =
		// commentHelper.getDistanceToTheRight(comment);
		// commentTableRight.put(Integer.valueOf(distanceToTheRight),
		// starterListRight);
		// starterListLeft.add(comment);
		// int distanceToTheLeft = commentHelper.getDistanceToTheLeft(comment);
		// commentTableLeft.put(Integer.valueOf(distanceToTheLeft),
		// starterListLeft);
		// commentHelper.addEquivalentKeys(distanceToTheLeft,
		// distanceToTheRight);
		// }
		// }
		//
		// commentHelper.resolvedTransitiveRelationsLeft(commentTableLeft);
		// commentHelper.resolvedTransitiveRelationsRight(commentTableRight);
		// commentHelper.decideOwner(commentTableLeft, commentTableRight);
	}

}
